package com.jinunn.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.jinunn.system.common.constant.SystemConstants;
import com.jinunn.system.common.model.Option;
import com.jinunn.system.entity.Menu;
import com.jinunn.system.mapper.MenuMapper;
import com.jinunn.system.service.MenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author JIN
 * @since 2024-07-11
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public List<Option<Long>> listMenuOptions() {
        List<Menu> menuList = this.lambdaQuery()
                .orderByDesc(Menu::getSort).list();
        return buildMenuOptions(SystemConstants.ROOT_NODE_ID, menuList);
    }

    /**
     * 递归生成菜单下拉层级列表
     *
     * @param parentId 父级ID
     * @param menuList 菜单列表
     * @return 菜单下拉列表
     */
    private List<Option<Long>> buildMenuOptions(Long parentId, List<Menu> menuList) {
        List<Option<Long>> menuOptions = new ArrayList<>();
        for (Menu menu : menuList) {
            if (menu.getParentId().equals(parentId)) {
                Option<Long> option = new Option<>(menu.getId(), menu.getName());
                List<Option<Long>> subMenuOptionList = buildMenuOptions(menu.getId(), menuList);
                if (CollectionUtil.isNotEmpty(subMenuOptionList)){
                    option.setChildren(subMenuOptionList);
                }
                menuOptions.add(option);
            }
        }
        return menuOptions;
    }
}
